"""
OpenAI代理问题修复工具
"""

import os
import sys
import time
import subprocess
from dotenv import load_dotenv

def check_pip_version():
    """检查pip版本"""
    try:
        pip_version = subprocess.check_output([sys.executable, "-m", "pip", "--version"]).decode("utf-8")
        print(f"当前pip版本: {pip_version.strip()}")
        return True
    except Exception as e:
        print(f"❌ 无法获取pip版本: {e}")
        return False

def update_pip():
    """更新pip到最新版本"""
    try:
        print("更新pip...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "pip"])
        return True
    except Exception as e:
        print(f"❌ 更新pip失败: {e}")
        return False

def check_openai_version():
    """检查OpenAI库版本"""
    try:
        import openai
        print(f"当前OpenAI库版本: {openai.__version__}")
        return openai.__version__
    except ImportError:
        print("❌ OpenAI库未安装")
        return None
    except Exception as e:
        print(f"❌ 检查OpenAI版本失败: {e}")
        return None

def update_openai():
    """更新OpenAI库到最新版本"""
    try:
        print("更新OpenAI库...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "openai"])
        return True
    except Exception as e:
        print(f"❌ 更新OpenAI库失败: {e}")
        return False

def test_openai_proxy():
    """测试OpenAI与代理连接"""
    load_dotenv()
    api_key = os.getenv("OPENAI-KEY")
    
    if not api_key:
        print("❌ 未找到OPENAI-KEY环境变量")
        return False
        
    http_proxy = os.getenv("HTTP_PROXY")
    https_proxy = os.getenv("HTTPS_PROXY")
    
    if not (http_proxy or https_proxy):
        print("⚠️ 未设置HTTP_PROXY或HTTPS_PROXY环境变量")
    else:
        print(f"HTTP代理: {http_proxy}")
        print(f"HTTPS代理: {https_proxy}")
    
    try:
        # 先清除现有的环境变量，避免之前设置的影响
        if "http_proxy" in os.environ:
            del os.environ["http_proxy"]
        if "https_proxy" in os.environ:
            del os.environ["https_proxy"]
        if "HTTP_PROXY" in os.environ:
            del os.environ["HTTP_PROXY"]
        if "HTTPS_PROXY" in os.environ:
            del os.environ["HTTPS_PROXY"]
            
        # 重新设置代理环境变量
        if http_proxy:
            os.environ["HTTP_PROXY"] = http_proxy
        if https_proxy:
            os.environ["HTTPS_PROXY"] = https_proxy
        
        print("环境变量设置完成")
        
        # 导入并初始化OpenAI客户端 - 注意只传递API密钥
        from openai import OpenAI
        client = OpenAI(api_key=api_key)
        # 不要在这里传入任何代理参数!
        
        # 测试API调用
        print("测试与OpenAI的连接...")
        start_time = time.time()
        models = client.models.list()
        elapsed = time.time() - start_time
        
        print(f"✅ 连接成功！响应时间: {elapsed:.2f}秒")
        print(f"检测到 {len(models.data)} 个模型")
        print("示例API调用:")
        print("```python")
        print("# 确保已设置环境变量HTTP_PROXY和HTTPS_PROXY")
        print("from openai import OpenAI")
        print("client = OpenAI(api_key=os.getenv('OPENAI-KEY'))")
        print("response = client.audio.speech.create(")
        print("    model='tts-1',")
        print("    voice='alloy',")
        print("    input='测试文本'")
        print(")")
        print("response.stream_to_file('speech.mp3')")
        print("```")
        
        return True
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False

def main():
    print("="*60)
    print("🛠️  OpenAI代理问题修复工具")
    print("="*60)
    
    # 检查并更新pip
    if check_pip_version():
        update_pip()
    
    # 检查并更新OpenAI库
    version = check_openai_version()
    if not version or version.split(".")[0] == "0":
        print("⚠️ 检测到OpenAI库需要更新（建议使用1.x版本）")
        update_openai()
        new_version = check_openai_version()
        if new_version:
            print(f"✅ OpenAI库已更新至 {new_version}")
    
    # 测试OpenAI与代理连接
    print("\n" + "="*60)
    print("🧪 测试OpenAI连接")
    print("="*60)
    success = test_openai_proxy()
    
    print("\n" + "="*60)
    if success:
        print("✅ 测试通过！OpenAI代理配置正常")
    else:
        print("❌ 测试失败！请检查以下事项:")
        print("1. 确保VPN/代理软件已启动")
        print("2. 确保.env文件中的代理配置准确")
        print("3. 确保OpenAI库版本是最新的（1.x）")
        print("4. 确保API密钥有效")
    print("="*60)

if __name__ == "__main__":
    main()
